import React, { useState } from 'react'
import {
  Button, Form, Input, notification,
} from 'antd'
import { connect } from '@umijs/max'
import JSEncrypt from '@/utils/JSEncrypt.js'
import styles from './index.less'

notification.config({
  maxCount: 3,
})

const isMobile = /iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone/i.test(navigator.userAgent)

const LoginForm = (props) => {
  const [captchaImg, setCaptchaImg] = useState(`${window.suanpan}/api/v1/kaptcha/get?t=${Math.random()}`)

  // useEffect(() => {
  //   props.dispatch({
  //     type: 'login/queryKaptcha',
  //     cb: (res) => {
  //       console.log('data', res)
  //       const url = `data:image/png;base64,${btoa(
  //         new Uint8Array(res)
  //           .reduce((data, byte) => data + String.fromCharCode(byte), ''),
  //       )}`
  //
  //       console.log('url', url)
  //     },
  //   })
  // }, [])

  const onFinish = (values) => {
    const { username, password, code } = values
    props.dispatch({
      type: 'login/queryLogin',
      params: {
        username: username?.trim(),
        password: JSEncrypt(password),
        code,
      },
      cb: (res) => {
        const {
          msg, status, data,
        } = res
        if (Number(status) === 200) {
          localStorage.setItem('loginSta', '1')
          // 实时获取最新的href
          if (data && data.isAuth == 2) {
            window.location = `${window.suanpan}#/managerial/space`
          } else if (data && data.isAuth == 3) {
            window.location = `${window.suanpan}#/managerial/q/role`
          } else if (data && data.isAuth == 4) {
            window.location = `${window.suanpan}#/managerial/logmanagement`
          } else {
            const backUrl = window.location.hash?.split('back=')?.[1]
            if (backUrl) {
              const isDetailH5 = /custom-form-ques-h5/.test(window.location.href)
              if (isMobile) {
                const newUrl = isDetailH5 ? backUrl : backUrl.replace(/custom-form-ques/g, 'custom-form-ques-h5')
                // history.push(`${decodeURIComponent(newUrl)}`)
                window.location = `${window.suanpan}#${decodeURIComponent(newUrl)}`
              } else if (isDetailH5) {
                const newUrl = isDetailH5 ? backUrl.replace(/custom-form-ques-h5/g, 'custom-form-ques') : backUrl
                window.location = `${window.suanpan}#${decodeURIComponent(newUrl)}`
                // history.push(`${decodeURIComponent(newUrl)}`)
              } else {
                // history.push(`${decodeURIComponent(backUrl)}`)
                window.location = `${window.suanpan}#${decodeURIComponent(backUrl)}`
              }
            } else {
              // history.push('/workSpace')
              window.location = `${window.suanpan}#/workSpace`
            }
          }
        } else {
          handleChangeCode()
          notification.error({
            description: msg || '服务端报错',
          })
          console.error(msg)
        }
      },
    })
  }

  const onFinishFailed = (errorInfo) => {
    console.warn('Failed:', errorInfo)
  }

  // 获取验证码
  const handleChangeCode = () => {
    setCaptchaImg(`${window.suanpan}/api/v1/kaptcha/get?t=${Math.random()}`)
  }

  return (
    <Form
      className={styles.login_form}
      name="basic"
      wrapperCol={{
        span: 24,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: '请输入邮箱/账号/手机号',
          },
        ]}
      >
        <Input placeholder="邮箱/账号/手机号" />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: '请输入密码',
          },
        ]}
      >
        <Input.Password placeholder="登录密码" />
      </Form.Item>

      <Form.Item
        name="code"
        rules={[
          {
            required: true,
            message: '请输入验证码',
          },
        ]}
      >
        <div>
          <Input className={styles.code} placeholder="验证码" />
          <img
            className={styles.code_img}
            onClick={handleChangeCode}
            src={captchaImg}
            alt="验证码"
          // src={this.state.imgurl}
          />
        </div>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className={styles.login_btn}>
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}

// const mapStateToProps = (state) => ({
//   test: state.home,
// })
//
// const mapDispatchToProps = () => ({
//
// })

export default connect(({ login }) => ({ ...login }))(LoginForm)
